﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Core.Base;
using Global.Mgr;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;

namespace Core.Mgrs
{
    public class ConfigMgr : BaseMgr
    {
        private List<string> configNames = new List<string>();
        private Dictionary<string, JObject> configs = new Dictionary<string, JObject>();

        public override void OnInit()
        {
            //初始化 configNames
            // configNames.Add("EmojiGameConfig");

            LoadGameConfigs();
        }

        /// <summary>
        /// 预加载配置表至缓存
        /// </summary>
        /// <param name="tuple"></param>
        public void LoadGameConfigs()
        {
            configs.Clear();
            int initCount = 0;
            Debug.Log("正在加载游戏配置...");
            foreach (var item in configNames)
            {
                GetGameConfig(item, delegate(JObject jObject)
                {
                    initCount++;
                    int residueNum = configNames.Count - initCount;
                    Debug.Log($"配置表{item}加载完成，剩余{residueNum}个");
                    configs.Add(item, jObject);
                    if (initCount >= configNames.Count)
                    {
                        Debug.Log("配置表加载完成");
                    }
                });
            }
        }

        /// <summary>
        /// 获取游戏配置
        /// </summary>
        /// <param name="configName">游戏配置名称(不需要加扩展名)</param>
        private void GetGameConfig(string configName, Action<JObject> cb)
        {
            string url = $"http://download.tapque.com/Innovate/BrainTraining/{configName}.json.txt";
            string downPath = AppConst.LocalConfigFilePath + $"{configName}.json.txt";
            KKGL.WebMgr.DownloadFile(url, downPath, null, delegate
            {
                string txt = Util.GetFileText(downPath);
                cb?.Invoke(JObject.Parse(txt));
            });
        }

        /// <summary>
        /// 获取配置表 逐级：缓存->local->Resources
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        public JObject GetConfig(string configName)
        {
#if KK_RELEASE
       //首先判断缓存中是否有配置表
            JObject configObj;
            if (configs.TryGetValue(configName, out configObj))
            {
                return configObj;
            }

            //从本地存储去找
            string downPath = AppConst.LocalConfigFilePath + $"{configName}.json.txt";
            if (Directory.Exists(downPath))
            {
                string txt = Util.GetFileText(downPath);
                var jObject = JObject.Parse(txt);
                configs.Add(configName, jObject);
                return jObject;
            }
#endif

            //从Resources中去找
            var asset = KKGL.ResMgr.Load<TextAsset>($"GameConfig/{configName}.json");
            return JObject.Parse(asset.text);
        }
    }
}